package demo8;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserMain {
    public int addUser(String username,String password) throws SQLException, ClassNotFoundException {
        Connection connection = SqlConnection.getCon();
        String sql = "INSERT INTO users(username, password) VALUES (?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        return preparedStatement.executeUpdate();
    }
    public Users login(String username, String password) throws SQLException, ClassNotFoundException {
        Users users = null;
        int i=1;
        Connection connection = SqlConnection.getCon();
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            users = new Users();
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
        }
        return users;
    }
    public static int deleteUser(int ID) throws SQLException, ClassNotFoundException {
        Connection connection = SqlConnection.getCon();
        String sql = "DELETE FROM users WHERE ID = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, ID);
        preparedStatement.executeUpdate();
        return ID;
    }
    public static int updateUser(int ID, String username) throws SQLException, ClassNotFoundException {
    Connection connection = SqlConnection.getCon();

    // 先检查用户名是否已存在
    String checkSql = "SELECT COUNT(*) FROM users WHERE username = ? AND ID != ?";
    try (PreparedStatement checkStmt = connection.prepareStatement(checkSql)) {
        checkStmt.setString(1, username);
        checkStmt.setInt(2, ID);
        try (ResultSet rs = checkStmt.executeQuery()) {
            if (rs.next() && rs.getInt(1) > 0) {
                System.out.println("用户名已存在");
                return 0;
            }
        }
    }
    String sql = "UPDATE users SET username = ? WHERE ID = ?";
    try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
        preparedStatement.setString(1, username);
        preparedStatement.setInt(2, ID);
        return preparedStatement.executeUpdate();
    }
}

}
